<?php
// +----------------------------------------------------------------------
// | [ api-yun.lib ] wo.pan
// +----------------------------------------------------------------------
// | Author: 北菜菜 <1440802@qq.com>
// +----------------------------------------------------------------------
namespace wopan;

include_once  __DIR__ . '/lib/WoPanAES.php';
include_once  __DIR__ . '/lib/WoPanChannel.php';
include_once  __DIR__ . '/lib/WoPanException.php';
include_once  __DIR__ . '/lib/WoPanRequest.php';
include_once  __DIR__ . '/lib/WoPanResponse.php';

// 引入通道类 ◆
include_once __DIR__ . '/lib/channel/ApiUser.php';
include_once __DIR__ . '/lib/channel/Wohome.php';

use wopan\lib\WoPanException;

/**
 * pan.wo 沃云盘Api
 * Class WoPan
 * @method \wopan\lib\channel\ApiUser apiUser()
 * @method \wopan\lib\channel\Wohome wohome()
 */
class WoPan
{
    // token表
    public static $tokens = [];

    private $channels = [];
    private $token = [];
    public function __construct($accessToken = null)
    {
        if (is_string($accessToken)) {
            $this->token['access_token'] = $accessToken;
        } else {
            self::$tokens[md5($accessToken['access_token'])] = $this->token = $accessToken;
        }
    }

    public function __call($name, $arguments)
    {
        $class = '\\wopan\lib\channel\\' . ucwords($name);
        if (class_exists($class)) {
            if (isset($this->channels[$name]) && $arguments !== true) {
                return $this->channels[$name];
            }
            return $this->channels[$name] = new $class($this->token['access_token']);
        }
        throw new WoPanException("channel $name not exists!");
    }

    // 登录
    public function appLoginV2($phone, $password, $uuid = '', $verifyCode = '')
    {
        $response = $this->apiUser()->appLoginV2($phone, $password, $uuid, $verifyCode);
        $token_file = __DIR__ . DIRECTORY_SEPARATOR . 'tokens' . DIRECTORY_SEPARATOR . $phone . '.log';
        file_put_contents($token_file, json_encode($response->data));
        foreach ($this->channels as $channel) {
            $channel->accessToken = $response->data['access_token'];
        }
        $this->token = $response->data;
        return $response;
    }
    // 使用本地缓存数据登录
    public static function localLogin($phone, $password)
    {
        $token_file = __DIR__ . DIRECTORY_SEPARATOR . 'tokens' . DIRECTORY_SEPARATOR . $phone . '.log';
        if (is_file($token_file)) {
            $token = json_decode(file_get_contents($token_file), true);
            if ($token['expires_time'] > time()) {
                return $self = new self($token);
            }
        }
        $self = new self();
        $self->token = $self->appLoginV2($phone, $password, '', '')->data;
        return $self;
    }
}
